package com.loong.service.impl;

import com.loong.mapper.CartMapper;
import com.loong.mapper.ProductMapper;
import com.loong.mapper.impl.CartMapperImpl;
import com.loong.mapper.impl.ProductMapperImpl;
import com.loong.pojo.Cart;
import com.loong.pojo.Product;
import com.loong.service.CartService;
import com.loong.utils.MybatisUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public class CartServiceImpl implements CartService {

    @Override
    public void createCart(int uid, int pid) throws InvocationTargetException, IllegalAccessException {
        CartMapper cartMapper = new CartMapperImpl();
        Cart cart = cartMapper.hasCart(uid, pid);
        if (cart != null) {
            cart.setCnum(cart.getCnum() + 1);
            cartMapper.updateCart(cart);
        }else {
            ProductMapper productMapper = new ProductMapperImpl();
            Product product = productMapper.selectProductByPid(pid);
            cart = new Cart();
            cart.setCnum(1);
            cart.setPid(pid);
            cart.setProduct(product);
            cart.setUid(uid);
            cartMapper.insertCart(cart);
        }
    }

    @Override
    public List<Cart> findAll(Integer uid) {
        CartMapper cartMapper = new CartMapperImpl();
        return cartMapper.selectCartsByUid(uid);
    }

    @Override
    public void deleteCartByCid(String cid) {
        CartMapper cartMapper = new CartMapperImpl();
        cartMapper.deleteCartByCid(cid);
    }

    @Override
    public void updateCartByCid(String cid, String price, String cnum) {
        BigDecimal bigDecimal = new BigDecimal(cnum);
        BigDecimal priceBig = new BigDecimal(cnum);
        BigDecimal cprice = priceBig.multiply(bigDecimal);

        int cnum2 = Integer.parseInt(cnum);
        CartMapper cartMapper = new CartMapperImpl();
        cartMapper.updateCartByCid(cprice,cnum2,cid);
    }

    @Override
    public void clearCart(String uid) {
        CartMapper cartMapper = new CartMapperImpl();
        int i = Integer.parseInt(uid);
        cartMapper.deleteCartByUid(i);
    }
}
